package com.szrt.javaweb.user.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.szrt.javaweb.user.entity.UserEntity;
import com.szrt.javaweb.utils.StringUtil;

public class UserServlet extends HttpServlet {

	private static final long serialVersionUID = 6732505991511216691L;
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String method = request.getParameter("method");
		
		if("register".equals(method)){
			register(request,response);
		}
		
	}

	@SuppressWarnings("unchecked")
	private void register(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		
		//1进行文件上传  保存到数据库中
		DiskFileItemFactory factory = new DiskFileItemFactory();

		factory.setSizeThreshold(1024*1024);
		
		
		File tempDirectory = new File("D:/szrtFile20161127");
		factory.setRepository(tempDirectory);

		ServletFileUpload upload = new ServletFileUpload(factory);

		upload.setSizeMax(1024*1024*1024);

		try {
			
			//把浏览传过来的所有数据  都封装成了1个list   FileItem
			List<FileItem> items = upload.parseRequest(request);
			Iterator<FileItem> iterator = items.iterator();
			
			
			//UserEntity entity = new UserEntity();
			Class<?> clazz = Class.forName("com.szrt.javaweb.user.entity.UserEntity");
			UserEntity entity =(UserEntity) clazz.newInstance();
			while(iterator.hasNext()){
				
				FileItem item = iterator.next();
				//System.err.println("key="+item.getFieldName() +",value=" +item.getString());
				
				/**
				 * true : null : phone
				 * true : null : password
				 * false : meimei.jpg : szrtFile
				 */
				//System.out.println(item.isFormField() +" : " +item.getName());
				
				//1flag如果等于true 就表示是普通的表单域(只要type!=file 就算  比如： text password checkbox radio...)
				
				boolean flag = item.isFormField();
				
				if(flag){
					
					String key   = item.getFieldName(); //phone password
					String value = item.getString();
					
					
					//已知 phone  调用  setPhone
					String methodName = StringUtil.getMethodName(key);
					Method method =clazz.getDeclaredMethod(methodName, String.class);
					method.invoke(entity, value);
					
					
					
					/*if("phone".equals(key)){
						entity.setPhone(value);
					}else if("password".equals(key)){
						entity.setPassword(value);
					}*/
					
					
					/**
					 * key=phone,value=13926583118
					 * key=password,value=123456	
					 */
					
				}else{
					
					//这里专门处理 type=file
					String fileName = item.getName();
					
					
					//得到  /upload/user这个目录在tomcate?
					String realPath =request.getSession().getServletContext().getRealPath("/upload/user/");
					//System.out.println(realPath + File.separator+fileName);
					
					//String path="/upload/user/"+fileName;
					
					
					
					
					//javaweb会把1个图片的信息封装到一个流中
					//D:/JavaTool/apache-tomcat-7.0.73/webapps/mvc-JavaWeb-Ajax-FileUpload/upload/user
					
					InputStream   in  = item.getInputStream();
					
					//读取到的流你要保存到哪里
					File  directory = new File(realPath);
					
					if(!directory.exists()){
						directory.mkdirs();
					}
					
					
					String uuid = UUID.randomUUID().toString();
					
					
					File  outFile = new File(realPath+File.separator+uuid+fileName.substring(fileName.lastIndexOf(".")));
					
					//System.out.println(realPath+File.separator+uuid+item.getContentType());
					entity.setPath("/upload/user/"+uuid+fileName.substring(fileName.lastIndexOf(".")));
					
					outFile.setWritable(true);
					
					writeStreamToFile(in, outFile);
					//读取这个流  并发这个结果写realPath
				}
			}
			
			request.getSession().setAttribute("user", entity);
			//System.out.println("########  " +new Gson().toJson(entity));
			//System.out.println(items.size());
			
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		
		response.sendRedirect(request.getServletContext().getContextPath() +"/user/success.jsp");
		
		
	}

	
	/**
	 * 
	 * @param in           表示从客户端接收到的文件
	 * @param outFile      表示写入到我们指定的地方
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private void writeStreamToFile(InputStream in, File outFile) throws FileNotFoundException, IOException {
		OutputStream  out = new FileOutputStream(outFile);
		
		
		//表示我1次性要多少多少个字节的数据
		byte b[] =new byte[1024*1024*10];
		
		//每一次读取了多少字节的数据
		int len=0;
		
		//int counter =0;
		long begin = System.currentTimeMillis();
		while((len =in.read(b)) != -1){
			//counter++;
			//System.out.println("counter="+counter);
			//System.out.println();
			
			
			//读到多少字节的数据我就写入多少字节的数据
			out.write(b, 0, len);
		}
		long end = System.currentTimeMillis();
		System.out.println("读取文件和写文件的时间="+(end-begin));
		
		out.flush();
		out.close();
	}

}
